package com.kamistoat.meimeimall.common.taskEngine;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class TaskEngineBeanUtils implements ApplicationContextAware {
    protected static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        TaskEngineBeanUtils.applicationContext = applicationContext;
    }

    public static Object getBeanByName(String name) throws BeansException {
        return TaskEngineBeanUtils.applicationContext.getBean(name);
    }

    public static <T> T getSingleBeanByType(Class<T> clazz) throws Exception {
        String[] beanDefinitionNames = TaskEngineBeanUtils.applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object beanByName = getBeanByName(beanDefinitionName);
            if(clazz.getName().equals(beanByName.getClass().getName())) {
                return (T) beanByName;
            }
        }
        throw new RuntimeException();
    }
}
